package org.gruposp2p.proyectokarma.gwt.client;

import java.util.Set;
import org.gruposp2p.proyectokarma.gwt.client.domain.SessionData;
import org.gruposp2p.proyectokarma.gwt.client.domain.Tag;
import org.gruposp2p.proyectokarma.gwt.client.event.EventBusManager;
import org.gruposp2p.proyectokarma.gwt.client.event.TagsEvent;
import org.gruposp2p.proyectokarma.gwt.client.json.JSONToDomain;
import org.gruposp2p.proyectokarma.gwt.client.ui.CentralPanel;
import org.gruposp2p.proyectokarma.gwt.client.ui.ErrorDialog;
import org.gruposp2p.proyectokarma.gwt.client.ui.TopPanel;
import org.gruposp2p.proyectokarma.gwt.client.util.Browser;
import org.gruposp2p.proyectokarma.gwt.client.util.RequestHelper;
import org.gruposp2p.proyectokarma.gwt.client.util.ServerPaths;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.ScrollPanel;

public class MainEntryPoint extends Composite implements EntryPoint, ValueChangeHandler<String>  {
	
    private static MainEntryPointBinder uiBinder = GWT.create(MainEntryPointBinder.class);
    
    interface MainEntryPointBinder extends UiBinder<ScrollPanel, MainEntryPoint> { }
    
    public static MainEntryPoint INSTANCE;
    
    @UiField ScrollPanel appPanel;
    @UiField TopPanel topPanel;
    @UiField CentralPanel centralPanel;
    
    public SessionData sessionData;
    public AppConstants constants;
    public Resources resources;

	public void onModuleLoad() {
    	INSTANCE = this;
		constants = GWT.create(AppConstants.class);
		resources = GWT.create(Resources.class);
    	sessionData = new SessionData();
    	appPanel = uiBinder.createAndBindUi(this);
    	RootPanel.get("ui").add(appPanel);
        History.addValueChangeHandler(this);
        String token = History.getToken();
        if (token.length() == 0) {
        	History.newItem(TopPanel.HISTORY_START);
        } else {
        	History.newItem(token);
        }
		String peer = com.google.gwt.user.client.Window.Location.getParameter("peer");
		if (peer != null) {
			//set authenticated
		}
    	RequestHelper.doGet(ServerPaths.getTagsPath(), 
    			new ServerRequestCallback());
        History.fireCurrentHistoryState();
	}


	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		String historyToken = event.getValue();
		centralPanel.setPanel(historyToken);
	}

	public CentralPanel getCentralPanel() {
		return centralPanel;
	}
	
	public TopPanel getTopPanel () {
		return topPanel;
	}
	
    private class ServerRequestCallback implements RequestCallback {

        @Override
    	public void onError(Request request, Throwable exception) {
        	new ErrorDialog().show("Exception", exception.getMessage());
        	Log.error(exception.getMessage());
    	}

        @Override
    	public void onResponseReceived(Request request, Response response) {
			Log.debug("StatusCode: " + response.getStatusCode() + 
					", Response Text: " + response.getText()); 
    		if (response.getStatusCode() == Response.SC_OK) {
                JSONValue jsonValue = JSONParser.parseLenient(response.getText());
    			Set<Tag> tagSet = JSONToDomain.getTags(jsonValue);
    			EventBusManager.getInstance().fireEvent(new TagsEvent(tagSet, TagsEvent.Action.OBTAINED));
    		} else if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {}
    		else {
            	new ErrorDialog().show("Error", "Response status: " 
            			+ response.getStatusCode());
    		}
    	}

    }
	
}
